<template>
  <view class="points-mall-page">
    <!-- 积分余额 -->
    <view class="points-header">
      <view class="points-label">当前积分</view>
      <view class="points-value">{{ points }}</view>
    </view>

    <!-- 积分兑换区 -->
    <view class="section-title">可兑换优惠券</view>
    <view class="coupon-list">
      <view
        class="coupon-card-new"
        v-for="item in couponList"
        :key="item.couponId"
      >
        <view class="coupon-main-row">
          <view class="coupon-info-col">
            <view class="coupon-title">{{ item.couponName }}</view>
            <view class="coupon-condition">
              <template v-if="item.couponType === 'FULL_MINUS'">
                满{{ item.minAmount }}元可用
              </template>
              <template v-else-if="item.couponType === 'INSTANT_REDUCTION'">
                无门槛使用
              </template>
              <template v-else>
                全场通用
              </template>
            </view>
          </view>
          <view class="coupon-value-btn-col">
            <view class="coupon-value-block">
              <view class="coupon-value">
                <template v-if="item.couponType === 'DISCOUNT'">
                  <text class="yuan">{{ (item.discount * 10).toFixed(1) }}</text>折
                </template>
                <template v-else>
                  <text class="yuan">￥</text>{{ item.reduceAmount }}
                </template>
              </view>
              <view class="need-points-label">{{ item.needPoint }}积分</view>
            </view>
            <button
              class="use-btn"
              :disabled="points < item.needPoint || item.couponStatus === 1"
              @tap="exchange(item)"
            >
              兑换
            </button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { couponApi, userApi } from '../../api/index.js'

// 用户积分
const points = ref(0)
// 用户ID
const customerId = ref(null)
// 优惠券列表
const couponList = ref([])

// 获取用户信息
const getUserInfo = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await userApi.getUserScore(token)
    if (res.code === 200) {
      // 从返回的数据中获取积分和用户ID
      points.value = res.data.point || 0
      customerId.value = res.data.customerId // 获取用户ID
      console.log('用户信息:', res.data) // 添加日志查看返回的数据结构
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 获取可兑换优惠券列表
const fetchCouponList = async () => {
  try {
    const res = await couponApi.getCouponList()
    if (res.code === 200) {
      couponList.value = res.data || []
    }
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    uni.showToast({
      title: '获取优惠券列表失败',
      icon: 'none'
    })
  }
}

// 兑换优惠券
const exchange = async (item) => {
  if (!customerId.value) {
    uni.showToast({ title: '用户信息获取失败', icon: 'none' })
    return
  }
  
  if (points.value < item.needPoint) {
    uni.showToast({ title: '积分不足', icon: 'none' })
    return
  }
  if (item.couponStatus === 1) {
    uni.showToast({ title: '优惠券已下架', icon: 'none' })
    return
  }
  
  try {
    const token = uni.getStorageSync('token')
    // 计算优惠券的过期时间（设置为7天后）
    const deadline_time = 7
    
    const res = await couponApi.exchangeCoupon(
      customerId.value,  // customer_id
      item.couponId,  // coupon_id
      deadline_time  // deadline_time
    )
    
    console.log('兑换优惠券返回:', res)  // 添加日志
    
    if (res.code === 200 && res.data === true) {
      // 计算新的积分值
      const newPoints = points.value - item.needPoint
      
      // 调用后端接口更新积分
      const updateRes = await userApi.updateUserScore(token, newPoints)
      console.log('更新积分结果:', updateRes)  // 添加日志
      
      if (updateRes.code === 200 && updateRes.data === true) {
        // 更新本地显示的积分
        points.value = newPoints
        
        uni.showToast({ 
          title: `兑换${item.couponName}成功`, 
          icon: 'success' 
        })
      } else {
        uni.showToast({
          title: '积分更新失败',
          icon: 'none'
        })
      }
    } else {
      uni.showToast({
        title: '兑换失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('兑换优惠券失败:', error)
    uni.showToast({
      title: '兑换失败',
      icon: 'none'
    })
  }
}

onMounted(() => {
  getUserInfo()
  fetchCouponList()
})

// 页面显示时重新获取用户信息
defineExpose({
  onShow() {
    getUserInfo()
  }
})
</script>

<style lang="scss" scoped>
.points-mall-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 32rpx;
}
.points-header {
  background: #057393;
  border-radius: 24rpx;
  margin: 32rpx 32rpx 24rpx 32rpx;
  padding: 40rpx 32rpx 32rpx;
  color: #fff;
  box-shadow: 0 8rpx 24rpx rgba(44, 62, 80, 0.15);
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 100%);
    z-index: 1;
  }
  
  .points-label {
    font-size: 28rpx;
    opacity: 0.9;
    margin-bottom: 12rpx;
    position: relative;
    z-index: 2;
  }
  
  .points-value {
    font-size: 48rpx;
    font-weight: bold;
    letter-spacing: 2rpx;
    position: relative;
    z-index: 2;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  }
}
.section-title {
  font-size: 32rpx;
  color: #057393;
  font-weight: 600;
  margin: 32rpx 32rpx 24rpx;
  position: relative;
  padding-left: 24rpx;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 6rpx;
    height: 28rpx;
    background: #057393;
    border-radius: 3rpx;
  }
}
.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  margin: 0 16rpx;
  padding: 10rpx 0 40rpx 0;
}
.coupon-card-new {
  background: #fff;
  border-radius: 18rpx;
  box-shadow: 0 2rpx 12rpx rgba(44, 62, 80, 0.08);
  padding: 0 0 0 0;
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
}
.coupon-main-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 20rpx 20rpx 24rpx;
}
.coupon-info-col {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.coupon-title {
  font-size: 30rpx;
  color: #222;
  font-weight: 600;
  margin-bottom: 10rpx;
}
.coupon-condition {
  font-size: 24rpx;
  color: #888;
  margin-bottom: 0;
}
.coupon-value-btn-col {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-width: 140rpx;
}
.coupon-value-block {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}
.coupon-value {
  font-size: 40rpx;
  color: #2196f3;
  font-weight: bold;
  margin-bottom: 2rpx;
  .yuan {
    font-size: 24rpx;
    margin-right: 2rpx;
  }
}
.need-points-label {
  font-size: 20rpx;
  color: #b0b8c1;
  margin-bottom: 10rpx;
  margin-top: 0;
  text-align: right;
}
.use-btn {
  background: #2196f3;
  color: #fff;
  font-size: 24rpx;
  border-radius: 32rpx;
  border: none;
  padding: 0 36rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-weight: 500;
  box-shadow: none;
  margin-top: 8rpx;
  margin-bottom: 0;
  transition: background 0.2s;
  align-self: flex-end;
}
.use-btn:active {
  background: #1976d2;
}
.use-btn[disabled] {
  background: #cfd8dc !important;
  color: #fff !important;
  opacity: 1;
}
</style>